package com.industrial.premu.service.impl;

import cn.hutool.bloomfilter.filter.SDBMFilter;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.KvDomain;
import com.industrial.premu.domain.PreMuBenefitEvaluation;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.vo.BgRespResultVo;
import com.industrial.premu.mapper.PreMuGenDocxMapper;
import com.industrial.premu.service.IPreMuGenDocxService;
import com.industrial.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BigDecimalTypeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PreMuGenDocxServiceImpl implements IPreMuGenDocxService {

    @Autowired
    private PreMuGenDocxMapper preMuGenDocxMapper;

    /**
     * <p>
     * 查询第一页的数据
     * </p>
     *
     * @return
     */
    @Override
    public Map<String, String> queryOnePageData() {

        PreMuBenefitEvaluation queryParams = new PreMuBenefitEvaluation();
        setQueryParams(queryParams);
        LocalDate localDate = LocalDate.now();
        queryParams.setYears(String.valueOf(localDate.getYear() - 1));

//        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.selectBenefitEvauationList(queryParams);
        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.queryOnePageDataList(queryParams);

        //查询上2年度的企业数据
        queryParams.setYears(String.valueOf(localDate.getYear() - 2));
//        List<PreMuBenefitEvaluation> prePreYearCompanyData = preMuGenDocxMapper.selectBenefitEvauationList(queryParams);
        List<PreMuBenefitEvaluation> prePreYearCompanyData = preMuGenDocxMapper.queryOnePageDataList(queryParams);

        if(result == null || result.isEmpty()){
            return new HashMap<>();
        }
        //计算上一年度年度规上企业的数量
        long preCompanyCount = result.stream().filter(i -> StringUtils.equals(i.getCompanyType(), "1")).count();
        long prePreCompanyCount;
        //计算上两年度的规上企业数量
        if(prePreYearCompanyData == null || prePreYearCompanyData.isEmpty()){
            prePreCompanyCount = 0L;
        }else{
            prePreCompanyCount = prePreYearCompanyData.stream().filter(i -> StringUtils.equals(i.getCompanyType(), "1")).count();
        }
        //上一年度增加多少加
        long icttpy = preCompanyCount - prePreCompanyCount;
        //计算企业档类的数量
        Map<String, Long> fixedQuantityMap = result.stream().filter(i -> !StringUtils.isBlank(i.getMjLevel())).collect(Collectors.groupingBy(PreMuBenefitEvaluation::getMjLevel, Collectors.counting()));
        long aCount = fixedQuantityMap.getOrDefault("A",0L);
        long bCount = fixedQuantityMap.getOrDefault("B",0L);
        long cCount = fixedQuantityMap.getOrDefault("C",0L);
        long dCount = fixedQuantityMap.getOrDefault("D",0L);

        Map<String,String> resultValue = new HashMap<>(16);
        resultValue.put("years",String.valueOf(localDate.getYear() - 1));
        resultValue.put("preYearCompanyCount",String.valueOf(preCompanyCount));
        resultValue.put("zjCompanyCount",String.valueOf(icttpy));

        resultValue.put("aCount",String.valueOf(aCount));
        resultValue.put("bCount",String.valueOf(bCount));
        resultValue.put("cCount",String.valueOf(cCount));
        resultValue.put("dCount",String.valueOf(dCount));
        //查询占应参评的占比
        PreMuCompanyInfo queryYcpParams = new PreMuCompanyInfo();
        queryYcpParams.setYear(String.valueOf(localDate.getYear() - 1));
        int ycpCompanyCount = preMuGenDocxMapper.selectYcpCompanyCount(queryYcpParams);
        //应参评的企业数量
        BigDecimal ycpCompanyCountBigDecimal = BigDecimal.valueOf(ycpCompanyCount);
        //当前年度企业数量
        BigDecimal curentCompanyCount  = BigDecimal.valueOf(preCompanyCount);
        if(ycpCompanyCountBigDecimal.compareTo(BigDecimal.ZERO) == 0){
            resultValue.put("zbYcpCompany","0");
        }else{
            BigDecimal zbYcpCompany = curentCompanyCount.multiply(BigDecimal.valueOf(100)).divide(ycpCompanyCountBigDecimal, 2, BigDecimal.ROUND_HALF_UP);
            resultValue.put("zbYcpCompany",zbYcpCompany.toString());
        }
        return resultValue;
    }

    /**
     * <p>
     * 查询第二页的数量
     * </p>
     *
     * @return
     */
    @Override
    public  Map<String,Object> queryTwoPageData() {

        PreMuBenefitEvaluation queryParams = new PreMuBenefitEvaluation();
        setQueryParams(queryParams);
        LocalDate localDate = LocalDate.now();
        queryParams.setYears(String.valueOf(localDate.getYear() - 1));
//        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.selectBenefitEvauationList(queryParams);
        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.queryTwoPageDataList(queryParams);

        result = result.stream().filter(i -> StringUtils.equals(i.getCompanyType(),"1")).collect(Collectors.toList());

        if(result == null || result.isEmpty()){
            Map<String,Object> resut = new HashMap<>();
            resut.put("sumAreaBigDecimal","0");
            resut.put("shuiShouBigDecimal","0");
            resut.put("xssrBigDecimal","0");
            resut.put("znh","0");
            resut.put("wrwpfdl","0");
            resut.put("yfjfzcBigDecimal","0");
            resut.put("npjzgrs","0");
            // 利润总额
            resut.put("lrze","0");
            return resut;
        }

        //用地面积
        BigDecimal sumAreaBigDecimal = result.stream().map(i -> {
            BigDecimal sumArea = i.getSumArea();
            if(sumArea == null){
                return BigDecimal.valueOf(0);
            }
            return sumArea;
        }).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);


        //税收
//        BigDecimal shuiShouBigDecimal = result.stream().map(PreMuBenefitEvaluation::getActualTax).reduce(BigDecimal::add).get();
        BigDecimal shuiShouBigDecimal = result.stream().map(i -> {
                    BigDecimal sumArea = i.getActualTax();
                    if(sumArea == null){
                        return BigDecimal.valueOf(0);
                    }
                    return sumArea;}).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L), 2, RoundingMode.HALF_UP);

        // 2025 新加的利润总额
        BigDecimal liRunZongEBigDecimal = result.stream().map(i -> {
                    BigDecimal profitTotal = i.getProfitTotal();
                    if(profitTotal == null){
                        return BigDecimal.valueOf(0);
                    }
                    return profitTotal;}).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L), 2, RoundingMode.HALF_UP);

        //销售收入
//        BigDecimal xssrBigDecimal = result.stream().map(PreMuBenefitEvaluation::getMainIncome).reduce(BigDecimal::add).get();
        BigDecimal xssrBigDecimal = result.stream().map(i -> {
            BigDecimal sumArea = i.getMainIncome();
            if(sumArea == null){
                return BigDecimal.valueOf(0);
            }
            return sumArea;}).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L), 2, RoundingMode.HALF_UP);

        //总能耗
//        double znh = result.stream().mapToDouble(i -> Double.valueOf(i.getTotalUsed())).sum();
        double znh = result.stream().mapToDouble(i -> Double.valueOf(StringUtils.isBlank(i.getTotalUsed()) ? "0" :i.getTotalUsed())).sum();
        if(znh != 0){
            BigDecimal divide = BigDecimal.valueOf(znh).divide(BigDecimal.valueOf(100000000L), 2, RoundingMode.HALF_UP);
            znh = divide.doubleValue();
        }
        //污染物排放
//        double wrwpfdl = result.stream().mapToDouble(i -> Double.valueOf(i.getTotalEquivalent())).sum();
        double wrwpfdl = result.stream().mapToDouble(i -> Double.valueOf(StringUtils.isBlank(i.getTotalEquivalent()) ? "0" :i.getTotalEquivalent())).sum();
        if(wrwpfdl != 0){
            BigDecimal divide = BigDecimal.valueOf(wrwpfdl).divide(BigDecimal.valueOf(10000L), 2, RoundingMode.HALF_UP);
            wrwpfdl = divide.doubleValue();
        }
        //研发经费支出
//        BigDecimal yfjfzcBigDecimal = result.stream().map(PreMuBenefitEvaluation::getRdFunds).reduce(BigDecimal::add).get();
        BigDecimal yfjfzcBigDecimal = result.stream().map(i -> {
            BigDecimal sumArea = i.getRdFunds();
            if(sumArea == null){
                return BigDecimal.valueOf(0);
            }
            return sumArea;}).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);

        //年平均职工人数
//        long npjzgrs = result.stream().mapToLong(PreMuBenefitEvaluation::getAnnualEmployees).sum();
        long npjzgrs = result.stream().mapToLong(i -> i.getAnnualEmployees() == null ? 0L :i.getAnnualEmployees() ).sum();
        if(npjzgrs != 0){
            BigDecimal divide = BigDecimal.valueOf(npjzgrs).divide(BigDecimal.valueOf(10000L), 2, RoundingMode.HALF_UP);
            npjzgrs = divide.longValue();
        }

        sumAreaBigDecimal = sumAreaBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        shuiShouBigDecimal = shuiShouBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        xssrBigDecimal = xssrBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        yfjfzcBigDecimal = yfjfzcBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        liRunZongEBigDecimal = liRunZongEBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal wrwpfdlBigDecimal = BigDecimal.valueOf(wrwpfdl);
        Map<String,Object> resut = new HashMap<>();
        resut.put("sumAreaBigDecimal",sumAreaBigDecimal.toString());
        resut.put("shuiShouBigDecimal",shuiShouBigDecimal.toString());
        resut.put("xssrBigDecimal",xssrBigDecimal.toString());
        resut.put("znh",znh);
        resut.put("wrwpfdl",wrwpfdlBigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP));
        resut.put("yfjfzcBigDecimal",yfjfzcBigDecimal.toString());
        resut.put("npjzgrs",npjzgrs);
        resut.put("lrze",liRunZongEBigDecimal.toPlainString());
        return resut;
    }

    /**
     * <p>
     *  查询第三页的数据
     * </p>
     *
     * @return
     */
    @Override
    public Map<String, Object> queryThreePageData() {
        PreMuBenefitEvaluation queryParams = new PreMuBenefitEvaluation();
        setQueryParams(queryParams);
        LocalDate localDate = LocalDate.now();
        queryParams.setYears(String.valueOf(localDate.getYear() - 1));
        Map<String,Object> result = preMuGenDocxMapper.queryThreePageData(queryParams);
        return result == null ? new HashMap<>() : result;
    }


    /**
     * <p>
     * 查询第四页的数据
     * </p>
     *
     * @return
     */
    @Override
    public Map<String, Object> queryFourPageData() {

        PreMuBenefitEvaluation queryParams = new PreMuBenefitEvaluation();
        setQueryParams(queryParams);
        LocalDate localDate = LocalDate.now();
        queryParams.setYears(String.valueOf(localDate.getYear() - 1));
//        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.selectBenefitEvauationList(queryParams);
        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.queryFourPageDataList(queryParams);

        Map<String,Object> r = new HashMap<>();
        if(result == null || result.isEmpty()){
            return new HashMap<>();
        }


        Map<String, List<PreMuBenefitEvaluation>> levelGroupMap = result.stream().filter(i -> !StringUtils.isBlank(i.getMjLevel())).collect(Collectors.groupingBy(PreMuBenefitEvaluation::getMjLevel));

        //参评企业总数
        long totalCount = result.stream().count();

        //所有企业的用地
        BigDecimal totalAreaBigDecimal = result.stream().map(PreMuBenefitEvaluation::getSumArea).reduce(BigDecimal::add).get();

        //所有企业的能耗
        BigDecimal totalNhDecimal = result.stream().map(i -> new BigDecimal(i.getTotalUsed())).reduce(BigDecimal::add).get();

        //所有企业的污染物排放
        BigDecimal totalWrwBigDecimal = null;
        try{
            totalWrwBigDecimal = result.stream().filter(i -> i.getTotalEquivalent() != null).map(i -> new BigDecimal(i.getTotalEquivalent())).reduce(BigDecimal::add).get();
        }catch (Exception e){
            e.printStackTrace();
        }

        //所有销售收入
        BigDecimal totalXssrBigDecimal = result.stream().map(PreMuBenefitEvaluation::getMainIncome).reduce(BigDecimal::add).get();

        //所有企业税收
        BigDecimal totalSsBigDecimal = result.stream().map(PreMuBenefitEvaluation::getActualTax).reduce(BigDecimal::add).get();

        //计算亩均税收平均值
        BigDecimal bigDecimal = BigDecimal.valueOf(totalCount);
        if(bigDecimal.compareTo(BigDecimal.ZERO) != 0 && totalAreaBigDecimal.compareTo(BigDecimal.ZERO) !=0 ){
            BigDecimal mjssAvg = totalSsBigDecimal.divide(totalAreaBigDecimal, 2, BigDecimal.ROUND_HALF_UP).divide(bigDecimal, 2, BigDecimal.ROUND_HALF_UP);
        }

        //研发投入强度
        BigDecimal yftrqd = result.stream().map(PreMuBenefitEvaluation::getScore4).reduce(BigDecimal::add).get();

        // 所有利润总额
        BigDecimal lrze = result.stream().map(PreMuBenefitEvaluation::getProfitTotal).reduce(BigDecimal::add).get();


        //循环计算
        for(Map.Entry<String,List<PreMuBenefitEvaluation>> item : levelGroupMap.entrySet()){

            Map<String,Object> tempMap = new HashMap<>(16);

            String key = item.getKey();
            List<PreMuBenefitEvaluation> value = item.getValue();


            //计算档类企业数量
            long count = value.stream().count();

            if(count != 0L){
                tempMap.put("aCompanyCount",count);

                //计算用地
                BigDecimal sumAreaBigDecimal = value.stream().map(PreMuBenefitEvaluation::getSumArea).reduce(BigDecimal::add).get();

                //税收贡献
                BigDecimal ssBigDecimal = value.stream().map(PreMuBenefitEvaluation::getActualTax).reduce(BigDecimal::add).get();

                // 利润总额
                BigDecimal lrzeBigDecimal = value.stream().map(PreMuBenefitEvaluation::getProfitTotal).reduce(BigDecimal::add).get();

                //销售收入
                BigDecimal xssrBigDecimal = value.stream().map(PreMuBenefitEvaluation::getMainIncome).reduce(BigDecimal::add).get();

                // 收入利润率 = 利润总额 / 销售收入 * 100%
                BigDecimal srlrlBigDecimal ;
                if(xssrBigDecimal.compareTo(BigDecimal.ZERO) == 0) {
                    srlrlBigDecimal = new BigDecimal("0");
                }else {
                    srlrlBigDecimal = lrzeBigDecimal.divide(xssrBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                }
                tempMap.put("srlrl", srlrlBigDecimal.toPlainString());

                //研发投入强度
                BigDecimal yftrqdBigDecimal = value.stream().map(i -> i.getScore4()).reduce(BigDecimal::add).get();

                //总能耗
                BigDecimal znhBigDecimal = value.stream().map(i -> {
                    return new BigDecimal(i.getTotalUsed());
                }).reduce(BigDecimal::add).get();

                //排放总当量
                BigDecimal pfzdlBigDecimal = value.stream().map(i -> new BigDecimal(i.getTotalEquivalent())).reduce(BigDecimal::add).get();

                //计算用地万亩
                sumAreaBigDecimal = sumAreaBigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
                tempMap.put("sumAreaBigDecimal",sumAreaBigDecimal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));
                //税收贡献
                ssBigDecimal = ssBigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
                tempMap.put("ssBigDecimal",ssBigDecimal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));
                // 利润总额
                lrzeBigDecimal = lrzeBigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
                tempMap.put("lrzeBigDecimal",lrzeBigDecimal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));
                //销售收入
                xssrBigDecimal = xssrBigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
                tempMap.put("xssrBigDecimal",xssrBigDecimal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));
                //能耗
                znhBigDecimal = znhBigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
                tempMap.put("znhBigDecimal",znhBigDecimal.divide(BigDecimal.valueOf(100000000L),2,RoundingMode.HALF_UP));
                //污染物排放
                pfzdlBigDecimal = pfzdlBigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
                tempMap.put("pfzdlBigDecimal",pfzdlBigDecimal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));


                //层级在企业总数中的占比
//                BigDecimal companyTotal = new BigDecimal(totalCount);
                BigDecimal companyTotal = new BigDecimal(count);
                BigDecimal zb = null;
                if(count == 0L){
                    zb = BigDecimal.valueOf(0);
                }else{
                    BigDecimal bigDecimal1 = BigDecimal.valueOf(totalCount);
                    if(bigDecimal1.compareTo(BigDecimal.ZERO) == 0){
                        zb = BigDecimal.ZERO;
                    }else{
                        zb = companyTotal.divide(bigDecimal1, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    }

                }
                tempMap.put("zb",zb);

                //用地占比
                if(totalAreaBigDecimal.compareTo(BigDecimal.ZERO) == 0){
                    tempMap.put("ydzb",0);
                }else{
                    BigDecimal ydzb = sumAreaBigDecimal.divide(totalAreaBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    tempMap.put("ydzb",ydzb);
                }

                //能耗占比
                if(totalNhDecimal.compareTo(BigDecimal.ZERO) == 0){
                    tempMap.put("nhzb",0);
                }else{
                    BigDecimal nhzb = znhBigDecimal.divide(totalNhDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    tempMap.put("nhzb",nhzb);
                }
                //排放占比
                if(totalWrwBigDecimal.compareTo(BigDecimal.ZERO) == 0){
                    tempMap.put("pfwrwZb",0);
                }else{
                    BigDecimal pfwrwZb = pfzdlBigDecimal.divide(totalWrwBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    tempMap.put("pfwrwZb",pfwrwZb);
                }

                //销售占比
                if(totalXssrBigDecimal.compareTo(BigDecimal.ZERO) == 0){
                    tempMap.put("xssrZb",0);
                }else{
                    BigDecimal xssrZb = xssrBigDecimal.divide(totalXssrBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    tempMap.put("xssrZb",xssrZb);
                }

                //税收
                if(totalSsBigDecimal.compareTo(BigDecimal.ZERO) == 0) {
                    tempMap.put("ssZb", "0");
                }else {
                    BigDecimal ssZb = ssBigDecimal.divide(totalSsBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    tempMap.put("ssZb",ssZb);
                }
                //利润总额
                if(lrze.equals(BigDecimal.ZERO)) {
                    tempMap.put("lrzeZb", "0");
                }else {
                    BigDecimal lrzeZb = lrzeBigDecimal.divide(lrze, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    tempMap.put("lrzeZb",lrzeZb);
                }
                //计算亩均税收
                if(sumAreaBigDecimal.compareTo(BigDecimal.ZERO) != 0){
//                    BigDecimal mjss = ssBigDecimal.divide(sumAreaBigDecimal, 2, BigDecimal.ROUND_HALF_UP).divide(BigDecimal.valueOf(count), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal mjss = ssBigDecimal.divide(sumAreaBigDecimal, 2, BigDecimal.ROUND_HALF_UP);
                    tempMap.put("mjss",mjss);
                }
                //研发投入强度
                if(yftrqd.compareTo(BigDecimal.ZERO) == 0){
                    tempMap.put("yftrqdZb",0);
                }else{
                    BigDecimal yftrqdZb = yftrqdBigDecimal.divide(yftrqd, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    tempMap.put("yftrqdZb",yftrqdZb);
                }

//                tempMap.put("mjssAvg",mjssAvg);

                r.put(key,tempMap);
            }
        }
        return r;
    }


    /**
     * 查询第18页数据
     *
     * @return
     */
    @Override
    public Map<String, Object> queryEighteenPageData() {
        PreMuBenefitEvaluation queryParams = new PreMuBenefitEvaluation();
        setQueryParams(queryParams);
        LocalDate localDate = LocalDate.now();
        queryParams.setYears(String.valueOf(localDate.getYear() - 1));
//        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.selectBenefitEvauationList(queryParams);
        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.queryEighteenPageDataList(queryParams);

        if(result == null || result.isEmpty()){
            return new HashMap<>();
        }

        //总量用地面积
        BigDecimal totalAreaBigDecimal = result.stream().map(PreMuBenefitEvaluation::getSumArea).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
        //总税收
        BigDecimal totalActualTaxBigDecimal = result.stream().map(PreMuBenefitEvaluation::getActualTax).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
        // 总利润总额
        BigDecimal totalProfitTotalBigDecimal = result.stream().map(PreMuBenefitEvaluation::getProfitTotal).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
        //销售收入
        BigDecimal totalMainIncomeBigDecimal = result.stream().map(PreMuBenefitEvaluation::getMainIncome).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
        //总能耗
        BigDecimal totalUsedBigDecimal = result.stream().map(i -> new BigDecimal(i.getTotalUsed())).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
        //排放总当量
        BigDecimal totalEquivalentBigDecimal = result.stream().map(i -> new BigDecimal(i.getTotalEquivalent())).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
        //研发经费支出
        BigDecimal totalRdFundsBigDecimal = result.stream().map(PreMuBenefitEvaluation::getRdFunds).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
        //年平均职工人数
        //long totalAnnualEmployees = result.stream().mapToLong(PreMuBenefitEvaluation::getAnnualEmployees).sum();
        BigDecimal totalAnnualEmployees = result.stream().map(i -> new BigDecimal(i.getAnnualEmployees())).reduce(BigDecimal::add).get().divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
        //totalAnnualEmployees = totalAnnualEmployees / 10000;
        /**
         * 查询省内用地面积排名前5的城市
         */
        List<BgRespResultVo> top5LandAreaMap = preMuGenDocxMapper.queryTop5LandAreaInProvince();

        BigDecimal top5SumArea = BigDecimal.valueOf(0);

        Map<String,Object> returnResultMap = new HashMap<>();

        Map<String,Object> landAreaResultMap = new HashMap<>(16);

        StringBuilder mjStr = new StringBuilder();

        for(BgRespResultVo item : top5LandAreaMap){
            String city = item.getCity();
            mjStr.append(city);
            BigDecimal areaMj = item.getValue();
            areaMj = areaMj == null ? BigDecimal.valueOf(0) : areaMj;
            areaMj = areaMj.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
            mjStr.append("(").append(areaMj).append("万亩)、");
            top5SumArea = top5SumArea.add(areaMj);
        }

        if(StringUtils.endsWith(mjStr.toString(),"、")){
            mjStr.deleteCharAt(mjStr.length() -1);
        }

        if(totalAreaBigDecimal.compareTo(BigDecimal.ZERO) == 0){
            landAreaResultMap.put("zb",0);
        }else{
            BigDecimal useLandAreaZb = top5SumArea.divide(totalAreaBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
            landAreaResultMap.put("zb",useLandAreaZb.toString());
        }

        landAreaResultMap.put("text",mjStr.toString());
        returnResultMap.put("ydmj",landAreaResultMap);


        //税收
        Map<String,Object> taxationResultMap = new HashMap<>(16);
        StringBuilder taxationText = new StringBuilder();
        BigDecimal top5Taxation = BigDecimal.valueOf(0);
        List<BgRespResultVo> top5TaxationMap = preMuGenDocxMapper.queryTop5TaxationInProvince();

        for(BgRespResultVo item : top5TaxationMap){

            String city = item.getCity();
            BigDecimal actualTax = item.getValue();
            BigDecimal temp = actualTax == null ? BigDecimal.valueOf(0) : actualTax;
            temp = temp.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
            taxationText.append(city);
            taxationText.append("(").append(temp).append("亿元)、");
//            taxationText.append("(").append(actualTax).append("亿元)、");
            top5Taxation = top5Taxation.add(temp);
        }
        if(StringUtils.endsWith(taxationText.toString(),"、")){
            taxationText.deleteCharAt(taxationText.length() -1);
        }
        if(totalActualTaxBigDecimal.compareTo(BigDecimal.ZERO) == 0) {
            taxationResultMap.put("text",taxationText.toString());
            taxationResultMap.put("zb", "0");
            returnResultMap.put("ss",taxationResultMap);
        }else {
            if(totalActualTaxBigDecimal.compareTo(BigDecimal.ZERO) == 0){
                taxationResultMap.put("zb",0);
            }else{
                BigDecimal taxationZb = top5Taxation.divide(totalActualTaxBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                taxationResultMap.put("zb",taxationZb.toString());
            }
            taxationResultMap.put("text",taxationText.toString());

            returnResultMap.put("ss",taxationResultMap);
        }

        // 利润总额
        Map<String,Object> lrzeMap = new HashMap<>(16);
        StringBuilder lrzeText = new StringBuilder();
        BigDecimal top5Lrze = BigDecimal.valueOf(0);
        List<BgRespResultVo> top5LrzeMap = preMuGenDocxMapper.queryTop5LrzeInProvince();

        for(BgRespResultVo item : top5LrzeMap){
            String city = item.getCity();
            BigDecimal lrze = item.getValue();
            BigDecimal temp = lrze == null ? BigDecimal.valueOf(0) : lrze;
            temp = temp.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
            lrzeText.append(city);
            lrzeText.append("(").append(temp).append("亿元)、");
            top5Lrze = top5Lrze.add(temp);
        }
        if(StringUtils.endsWith(lrzeText.toString(),"、")){
            lrzeText.deleteCharAt(lrzeText.length() -1);
        }
        if(totalProfitTotalBigDecimal.compareTo(BigDecimal.ZERO) == 0){
            lrzeMap.put("zb",0);
        }else{
            BigDecimal lrzeZb = top5Lrze.divide(totalProfitTotalBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
            lrzeMap.put("zb",lrzeZb.toPlainString());
        }

        lrzeMap.put("text",lrzeText.toString());

        returnResultMap.put("lrze",lrzeMap);


        //销售收入
        Map<String,Object> mainIncomeResultMap = new HashMap<>(16);
        BigDecimal top5MainIncome = BigDecimal.valueOf(0);
        StringBuilder mainIncomeText = new StringBuilder();
        List<BgRespResultVo> top5MainIncomeMap = preMuGenDocxMapper.queryTop5MainIncomeInProvince();
        for(BgRespResultVo item : top5MainIncomeMap){

            String city = item.getCity();
            mainIncomeText.append(city);
            BigDecimal mainIncome = item.getValue();
            BigDecimal temp = mainIncome == null ? BigDecimal.valueOf(0) : mainIncome;
            temp = temp.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
            mainIncomeText.append("(").append(temp).append("亿元)、");
//            mainIncomeText.append("(").append(mainIncome).append("亿元)、");
            top5MainIncome = top5MainIncome.add(temp);
        }

        if(StringUtils.endsWith(mainIncomeText.toString(),"、")){
            mainIncomeText.deleteCharAt(mainIncomeText.length() -1);
        }

        if(totalMainIncomeBigDecimal.compareTo(BigDecimal.ZERO) == 0){
            mainIncomeResultMap.put("zb",0);

        }else{
            BigDecimal mainIncomeZb = top5MainIncome.divide(totalMainIncomeBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
            mainIncomeResultMap.put("zb",mainIncomeZb.toString());
        }
        mainIncomeResultMap.put("text",mainIncomeText.toString());
        returnResultMap.put("xssr",mainIncomeResultMap);


        //总能耗
        Map<String,Object> totalUsedResultMap = new HashMap<>(16);
        BigDecimal top5TotalUsed = BigDecimal.valueOf(0);
        List<BgRespResultVo> top5TotalUsedMap = preMuGenDocxMapper.queryTop5TotalUsedInProvince();
        StringBuilder totalUsedStr = new StringBuilder();
        for(BgRespResultVo item : top5TotalUsedMap){
            String city = item.getCity();
            totalUsedStr.append(city);
            BigDecimal totalUsed = item.getValue() == null ? BigDecimal.ZERO : item.getValue();
            totalUsed = totalUsed.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
            totalUsedStr.append("(").append(totalUsed).append("万吨标煤)、");
//            totalUsedStr.append("(").append(totalUsed).append("万吨标煤)、");
            top5TotalUsed = top5TotalUsed.add(totalUsed);
        }

        if(StringUtils.endsWith(totalUsedStr.toString(),"、")){
            totalUsedStr.deleteCharAt(totalUsedStr.length() -1);
        }
        if(totalUsedBigDecimal.compareTo(BigDecimal.ZERO) == 0 ){
            totalUsedResultMap.put("zb",0);

        }else{
            BigDecimal usedZb = top5TotalUsed.divide(totalUsedBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
            totalUsedResultMap.put("zb",usedZb.toString());
        }
        totalUsedResultMap.put("text",totalUsedStr.toString());
        returnResultMap.put("znh",totalUsedResultMap);

        //污染物排放总量
        Map<String,Object> totalEquivalentResultMap = new HashMap<>(16);
        BigDecimal top5TotalEquivalent = BigDecimal.valueOf(0);
        List<BgRespResultVo> top5TotalEquivalentMap = preMuGenDocxMapper.queryTop5TotalEquivalentInProvince();
        StringBuilder totalEquivalentStr = new StringBuilder();
        for(BgRespResultVo item : top5TotalEquivalentMap){

            String city = item.getCity();
            totalEquivalentStr.append(city);
            BigDecimal totalEquivalent = item.getValue();
            BigDecimal temp = totalEquivalent == null ? BigDecimal.valueOf(0) : totalEquivalent;
            temp = temp.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
            totalEquivalentStr.append("(").append(temp).append("万吨)、");
//            totalEquivalentStr.append("(").append(totalEquivalent).append("万吨)、");
            top5TotalEquivalent = top5TotalEquivalent.add(temp);

        }

        if(StringUtils.endsWith(totalEquivalentStr.toString(),"、")){
            totalEquivalentStr.deleteCharAt(totalEquivalentStr.length() -1);
        }

        if(totalEquivalentBigDecimal.compareTo(BigDecimal.ZERO) == 0){
            totalEquivalentResultMap.put("zb",0);

        }else{
            BigDecimal totalEquivalentZb = top5TotalEquivalent.divide(totalEquivalentBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
            totalEquivalentResultMap.put("zb",totalEquivalentZb.toString());
        }
        totalEquivalentResultMap.put("text",totalEquivalentStr.toString());
        returnResultMap.put("wrpfzl",totalEquivalentResultMap);

        //研发经费投入
        Map<String,Object> rdFundsResultMap = new HashMap<>(16);
        BigDecimal top5RdFunds = BigDecimal.valueOf(0);
        StringBuilder rdFundsStr = new StringBuilder();
        List<Map<String,Object>> top5RdFundsMap = preMuGenDocxMapper.queryTop5RdFundsInProvince();
        for(Map<String,Object> item : top5RdFundsMap){
            String city = (String) item.get("city");
            rdFundsStr.append(city);
            BigDecimal rdFunds = (BigDecimal)item.get("rdFunds");
            BigDecimal temp = rdFunds == null ? BigDecimal.valueOf(0) : rdFunds;
            temp = temp.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
            rdFundsStr.append("(").append(temp).append("亿元)、");
//            rdFundsStr.append("(").append(rdFunds).append("亿元)、");

            top5RdFunds = top5RdFunds.add(temp);
        }
        if(StringUtils.endsWith(rdFundsStr.toString(),"、")){
            rdFundsStr.deleteCharAt(rdFundsStr.length() -1);
        }
        if(totalRdFundsBigDecimal.compareTo(BigDecimal.ZERO) == 0){
            rdFundsResultMap.put("zb",0);
        }else{
            BigDecimal rdFundsZb = top5RdFunds.divide(totalRdFundsBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
            rdFundsResultMap.put("zb",rdFundsZb.toString());
        }
        rdFundsResultMap.put("text",rdFundsStr.toString());
        returnResultMap.put("yfjf",rdFundsResultMap);

        //年平均职工人数
        Map<String,Object> annualEmployeesResultMap = new HashMap<>(16);
        BigDecimal top5AnnualEmployees = BigDecimal.valueOf(0);
        StringBuilder annualEmployeesStr = new StringBuilder();
        List<Map<String,Object>> top5AnnualEmployeesMap = preMuGenDocxMapper.queryTop5AnnualEmployeesInProvince();
        for(Map<String,Object> item : top5AnnualEmployeesMap){
            String city = (String) item.get("city");
            annualEmployeesStr.append(city);
            BigDecimal annualEmployees = (BigDecimal)item.get("annualEmployees");
            BigDecimal temp = annualEmployees == null ? BigDecimal.valueOf(0) : annualEmployees;
            temp = temp.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP);
            annualEmployeesStr.append("(").append(temp).append("万人)、");
//            annualEmployeesStr.append("(").append(annualEmployees).append("万人)、");
            top5AnnualEmployees = top5AnnualEmployees.add(temp);
        }
        if(StringUtils.endsWith(annualEmployeesStr.toString(),"、")){
            annualEmployeesStr.deleteCharAt(annualEmployeesStr.length() - 1);
        }
        if(totalAnnualEmployees.compareTo(BigDecimal.ZERO) == 0){
            annualEmployeesResultMap.put("zb",0);
        }else{
            BigDecimal annualEmployeesZb = top5AnnualEmployees.divide(totalAnnualEmployees, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
            annualEmployeesResultMap.put("zb",annualEmployeesZb.toString());
        }
        annualEmployeesResultMap.put("text",annualEmployeesStr.toString());
        returnResultMap.put("zgrs",annualEmployeesResultMap);
        return returnResultMap;
    }


    /**
     * 查询规下企业参评情况
     *
     * @return
     */
    @Override
    public AjaxResult queryMicroIndustrialEnterprisesParticipation() {

        //查询规下企业有多少参评的
        int year = DateUtil.year(DateUtils.getNowDate()) - 1;
        PreMuBenefitEvaluation queryParams = new PreMuBenefitEvaluation();
        queryParams.setProvince("370000");
        queryParams.setYears(String.valueOf(year));
        queryParams.setCompanyType("2");
//        List<PreMuBenefitEvaluation> currentMuBenefitEvaluations = preMuGenDocxMapper.selectBenefitEvauationList(queryParams);
        List<PreMuBenefitEvaluation> currentMuBenefitEvaluations = preMuGenDocxMapper.queryMicroIndustrialEnterprisesParticipation(queryParams);

        year = DateUtil.year(DateUtils.getNowDate()) - 2;
        queryParams.setYears(String.valueOf(year));
//        List<PreMuBenefitEvaluation> preMuBenefitEvaluations = preMuGenDocxMapper.selectBenefitEvauationList(queryParams);
        List<PreMuBenefitEvaluation> preMuBenefitEvaluations = preMuGenDocxMapper.queryMicroIndustrialEnterprisesParticipation(queryParams);

        Map<String,Object> resultMap = new HashMap<>(16);

        //当前年有多少家规下企业
        int currentCompanyCount = currentMuBenefitEvaluations.size();
        int preCompanyCount = preMuBenefitEvaluations.size();

        //比上一年增家多少家
        int addCompanyCount = currentCompanyCount - preCompanyCount;

        resultMap.put("currentCompanyCount",currentCompanyCount);
        //上一年增加企业数
        resultMap.put("addCompanyCount",addCompanyCount);

        //总用地
        BigDecimal sumAreaTotal = new BigDecimal(0);
        //总税收
        BigDecimal actualTaxTotal = new BigDecimal(0);
        //销售收入
        BigDecimal mainIncomeTotal = new BigDecimal(0);
        // 利润总额
        BigDecimal profitTotal = new BigDecimal(0);

        //计算共占地多少亩
        for(PreMuBenefitEvaluation item : currentMuBenefitEvaluations){
            BigDecimal sumArea = item.getSumArea();
            sumAreaTotal = sumAreaTotal.add(sumArea);

            BigDecimal actualTax = item.getActualTax();
            actualTaxTotal = actualTaxTotal.add(actualTax);

            BigDecimal mainIncome = item.getMainIncome();
            mainIncomeTotal = mainIncomeTotal.add(mainIncome);

            BigDecimal profit = item.getProfitTotal();
            profitTotal = profitTotal.add(profit);
        }

        //查询规上工业企业的亩均税收和亩均销售
        Map<String,Object> gsMjssAndMjxs = preMuGenDocxMapper.selectGsMjssAndMjxs();

        if(gsMjssAndMjxs != null){
            BigDecimal gsMjss = (BigDecimal)gsMjssAndMjxs.get("mjss");
            BigDecimal gsMjxssr = (BigDecimal)gsMjssAndMjxs.get("mjxssr");

            if(sumAreaTotal.compareTo(BigDecimal.ZERO) != 0){
                if(sumAreaTotal.compareTo(BigDecimal.ZERO) != 0){
                    //亩均税收
                    BigDecimal mjssBigDecimal = actualTaxTotal.divide(sumAreaTotal, 2, BigDecimal.ROUND_HALF_UP);
                    resultMap.put("mjssBigDecimal",mjssBigDecimal);

                    //亩均销售收入
                    BigDecimal mjxssrBigDecimal = mainIncomeTotal.divide(sumAreaTotal, 2, BigDecimal.ROUND_HALF_UP);
                    resultMap.put("mjxssrBigDecimal",mjxssrBigDecimal);

                    if(gsMjss != null && gsMjss.compareTo(BigDecimal.ZERO) != 0){
                        BigDecimal gsZbMjss = mjssBigDecimal.divide(gsMjss, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                        resultMap.put("gsZbMjss",gsZbMjss);
                    }else{
                        resultMap.put("gsZbMjss","-");
                    }

                    if(gsMjxssr != null && gsMjxssr.compareTo(BigDecimal.ZERO) != 0){
                        BigDecimal gsZbMjxs = mjxssrBigDecimal.divide(gsMjxssr, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                        resultMap.put("gsZbMjxs",gsZbMjxs);
                    }else{
                        resultMap.put("gsZbMjxs","-");
                    }

                }else{
                    resultMap.put("mjssBigDecimal","-");
                    resultMap.put("mjxssrBigDecimal","-");
                    resultMap.put("gsZbMjxs","-");
                    resultMap.put("gsZbMjss","-");
                }
            }
        }else{
            resultMap.put("mjssBigDecimal","-");
            resultMap.put("mjxssrBigDecimal","-");
            resultMap.put("gsZbMjxs","-");
            resultMap.put("gsZbMjss","-");
        }




        resultMap.put("sumAreaTotal",sumAreaTotal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));
        resultMap.put("actualTaxTotal",actualTaxTotal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));
        resultMap.put("mainIncomeTotal",mainIncomeTotal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));
        // 利润总额
        resultMap.put("lrzeTotal",profitTotal.divide(BigDecimal.valueOf(10000L),2,RoundingMode.HALF_UP));
        // 收入利润率
        BigDecimal srlrl = new BigDecimal("0");
        if(mainIncomeTotal.compareTo(BigDecimal.ZERO) > 0) {
            srlrl = profitTotal.divide(mainIncomeTotal, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
        }
        resultMap.put("srlrl", srlrl);
        // 收入利润率占规上企业的百分比
        if(gsMjssAndMjxs == null) {
            resultMap.put("gsSrlrlZb", "-");
        }else {
            Object o = gsMjssAndMjxs.get("srlrl");
            if(o == null) {
                resultMap.put("gsSrlrlZb", "-");
            }else {
                BigDecimal srlrlPercent = (BigDecimal) o;
                if(srlrlPercent.compareTo(BigDecimal.ZERO) == 0) {
                    resultMap.put("gsSrlrlZb", "-");
                }else {
                    BigDecimal srlrlzb = srlrl.divide(srlrlPercent, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                    resultMap.put("gsSrlrlZb", srlrlzb);
                }
            }
        }

        return AjaxResult.success(resultMap);
    }

    /**
     * 查询全员劳动生产力
     *
     * @return
     */
    @Override
    public AjaxResult queryTotalLaborProductivity() {
        List<KvDomain> result = preMuGenDocxMapper.queryTotalLaborProductivity();

        BigDecimal maxBigDecimal = new BigDecimal(0);
        BigDecimal totalBigDecimal = new BigDecimal(0);
        String znbCity = "";
        for(KvDomain item : result){
//            BigDecimal currentValue = item.get("annualEmployees") == null ? BigDecimal.valueOf(0) : (BigDecimal) item.get("annualEmployees");
//            totalBigDecimal = totalBigDecimal.add(currentValue);
//            if(currentValue.compareTo(maxBigDecimal) == 1){
//                maxBigDecimal = currentValue;
//                znbCity = (String) item.get("city");
//            }

            BigDecimal currentValue = item.getResultValueBigDecimal() == null ? BigDecimal.valueOf(0) : item.getResultValueBigDecimal();
            totalBigDecimal = totalBigDecimal.add(currentValue);
            if(currentValue.compareTo(maxBigDecimal) == 1){
                maxBigDecimal = currentValue;
                znbCity = item.getName();
            }

        }

        BigDecimal pjz = totalBigDecimal.divide(BigDecimal.valueOf(16), 2, BigDecimal.ROUND_HALF_UP);
        int count = 0;
        StringBuilder gypjzCity = new StringBuilder();
        for(KvDomain item : result){
//            BigDecimal currentValue = item.get("annualEmployees") == null ? BigDecimal.valueOf(0) : (BigDecimal) item.get("annualEmployees");
//            totalBigDecimal = totalBigDecimal.add(currentValue);
//            if(currentValue.compareTo(pjz) == 1){
//                count++;
//                gypjzCity.append(item.get("city")).append("、");
//            }

            BigDecimal currentValue = item.getResultValueBigDecimal() == null ? BigDecimal.valueOf(0) : item.getResultValueBigDecimal();
            totalBigDecimal = totalBigDecimal.add(currentValue);
            if(currentValue.compareTo(pjz) == 1){
                count++;
                gypjzCity.append(item.getName()).append("、");
            }
        }
        if(StringUtils.endsWith(gypjzCity.toString(),"、")){
            gypjzCity.deleteCharAt(gypjzCity.length() - 1);
        }

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("gypjzCount",count);
        resultMap.put("gypjzCity",gypjzCity.toString());
        resultMap.put("znbCity",znbCity.toString());
        resultMap.put("znbCityValue",maxBigDecimal.toString());
        resultMap.put("pjz",pjz.toString());
        return AjaxResult.success(resultMap);
    }

    /**
     * 各市研发经费投入强度
     * @return
     */
    @Override
    public AjaxResult queryResearchExpenditureIntensity() {
        List<KvDomain> result = preMuGenDocxMapper.queryResearchExpenditureIntensity();
        BigDecimal maxBigDecimal = new BigDecimal("0");
        BigDecimal totalBigDecimal = new BigDecimal("0");
        String znbCity = "";
        for(KvDomain item : result){
//            BigDecimal currentValue = item.get("yfjftrqd") == null ? BigDecimal.valueOf(0) : (BigDecimal) item.get("yfjftrqd");
//            if(currentValue.compareTo(maxBigDecimal) == 1){
//                maxBigDecimal = currentValue;
//                znbCity = (String) item.get("city");
//            }

            BigDecimal currentValue = item.getResultValueBigDecimal() == null ? BigDecimal.valueOf(0) : item.getResultValueBigDecimal();
            if(currentValue.compareTo(maxBigDecimal) == 1){
                maxBigDecimal = currentValue;
                znbCity = item.getName();
            }
            totalBigDecimal = totalBigDecimal.add(currentValue);
        }

        //计算平均值
        BigDecimal pjz = totalBigDecimal.divide(BigDecimal.valueOf(16), 2, BigDecimal.ROUND_HALF_UP);
        StringBuilder dypjzCity = new StringBuilder();
        int count = 0;
        //查询高于平均值的市
        for(KvDomain item : result){
//            BigDecimal currentValue = item.get("yfjftrqd") == null ? BigDecimal.valueOf(0) : (BigDecimal) item.get("yfjftrqd");
//            if(currentValue.compareTo(pjz) == 1){
//                dypjzCity.append(item.get("city")).append("、");
//                count++;
//            }

            BigDecimal currentValue = item.getResultValueBigDecimal() == null ? BigDecimal.ZERO : item.getResultValueBigDecimal();
            if(currentValue.compareTo(pjz) == 1){
                dypjzCity.append(item.getName()).append("、");
                count++;
            }

            if(StringUtils.endsWith(dypjzCity.toString(),"、")){
                dypjzCity.deleteCharAt(dypjzCity.length() -1);
            }

        }
        Map<String,Object> resultMap = new HashMap<>(16);
        resultMap.put("pjz",pjz.toString());
        resultMap.put("dypjzCityCount",count);
        resultMap.put("dypjzCity",dypjzCity.toString());
        resultMap.put("znbCity",znbCity);
        resultMap.put("znbCityValue",maxBigDecimal.toString());
        return AjaxResult.success(resultMap);
    }

    /**
     * 查询单位污染物排放销售收入
     * @return
     */
    @Override
    public AjaxResult queryUnitPollutantEmissionSalesIncome() {
        List<KvDomain> maps = preMuGenDocxMapper.queryUnitPollutantEmissionSalesIncome();

        List<KvDomain> pjz = preMuGenDocxMapper.queryProvinceAveragePollutantEmissionSalesIncome();
//        BigDecimal pjzBigDecimal = pjz.get("totalEquivalentAvg") == null ? BigDecimal.valueOf(0) : BigDecimal.valueOf((Double) pjz.get("totalEquivalentAvg"));

        BigDecimal sum = new BigDecimal(0);
        BigDecimal avg = new BigDecimal(0);
        for(KvDomain item : pjz){
//            Double totalEquivalentAvg = item.get("totalEquivalentAvg") == null ? 0d : (Double) item.get("totalEquivalentAvg");
//            BigDecimal totalEquivalentAvgBigDeciaml = BigDecimal.valueOf(totalEquivalentAvg);

            BigDecimal totalEquivalentAvg = item.getResultValueBigDecimal() == null ? BigDecimal.ZERO : item.getResultValueBigDecimal();
            sum = sum.add(totalEquivalentAvg);
        }
        avg = sum.divide(BigDecimal.valueOf(16),2,BigDecimal.ROUND_HALF_UP);
        Map<String,Object> resultMap = new HashMap<>(16);

        //排放量第一
        if(maps != null && !maps.isEmpty()){
            //排名第一的城市
            KvDomain oneMap = maps.get(0);
            resultMap.put("one",oneMap.getName());
        }
        StringBuilder heigAvg = new StringBuilder();
        int heigCityCount = 0;
        for(KvDomain item : maps){
//            String city = (String) item.get("city");
//            Double totalEquivalent = (Double)item.get("totalEquivalent");

            String city = item.getName();
            BigDecimal totalEquivalent = item.getResultValueBigDecimal();

//            BigDecimal currentCity = totalEquivalent == null ? BigDecimal.valueOf(0) : new BigDecimal(totalEquivalent);
            BigDecimal currentCity = totalEquivalent == null ? BigDecimal.valueOf(0) : totalEquivalent;
            if(currentCity.compareTo(avg) == 1){
                heigCityCount++;
                heigAvg.append(city).append("、");
            }
        }
        if(StringUtils.endsWith(heigAvg.toString(),"、")){
            heigAvg.deleteCharAt(heigAvg.length() -1);
        }
        resultMap.put("heigAvg",heigAvg.toString());
        resultMap.put("heigCityCount",heigCityCount);
        resultMap.put("pjz",avg.toString());
        return AjaxResult.success(resultMap);
    }

    /**
     * 查询23页的数据
     *
     * @return
     */
    @Override
    public Map<String, Object> queryTwentyThree() {
        PreMuBenefitEvaluation queryParams = new PreMuBenefitEvaluation();
        setQueryParams(queryParams);
        LocalDate localDate = LocalDate.now();
        queryParams.setYears(String.valueOf(localDate.getYear() - 1));
        List<PreMuBenefitEvaluation> result = preMuGenDocxMapper.selectBenefitEvauationList(queryParams);
        Map<String,Object> resultMap = new HashMap<>(16);
        if(result == null || result.isEmpty()){
            return resultMap;
        }

        //计算亩均税收
        List<Map<String, Object>> cityAverageTaxPerAcre = preMuGenDocxMapper.queryProvinceCityAverageTaxPerAcre();
        Map<String,Object> mjss = new HashMap<>();

        if(cityAverageTaxPerAcre != null && cityAverageTaxPerAcre.size() == 2){
            Map<String, Object> zeroMap = cityAverageTaxPerAcre.get(0);
            Map<String, Object> oneMap = cityAverageTaxPerAcre.get(1);
            String zeroCity = (String) zeroMap.get("city");
            String oneCity = (String) oneMap.get("city");
            Object zeroMjss = zeroMap.get("mjss");
            Object oneMjss= oneMap.get("mjss");
            mjss.put("city",zeroCity + "、" + oneCity);
            mjss.put("zeroMjss",zeroMjss);
            mjss.put("oneMjss",oneMjss);
        }else if(cityAverageTaxPerAcre != null && cityAverageTaxPerAcre.size() == 1){
            Map<String, Object> zeroMap = cityAverageTaxPerAcre.get(0);
            String zeroCity = (String)zeroMap.get("city");
            Object zeroMjss = zeroMap.get("mjss");
            mjss.put("city",zeroCity);
            mjss.put("zeroMjss",zeroMjss);
            mjss.put("oneMjss","0");
        }
        resultMap.put("mjss",mjss);

        // 收入利润率
        List<Map<String, Object>> cityAverageSrlrlPerAcre = preMuGenDocxMapper.queryProvinceCityAverageSrlrlPerAcre();
        Map<String,Object> srlrl = new HashMap<>();

        if(cityAverageSrlrlPerAcre != null && cityAverageSrlrlPerAcre.size() == 2){
            Map<String, Object> zeroMap = cityAverageSrlrlPerAcre.get(0);
            Map<String, Object> oneMap = cityAverageSrlrlPerAcre.get(1);
            String zeroCity = (String) zeroMap.get("city");
            String oneCity = (String) oneMap.get("city");
            Object zeroMjss = zeroMap.get("srlrl");
            Object oneMjss= oneMap.get("srlrl");
            srlrl.put("city",zeroCity + "、" + oneCity);
            srlrl.put("zeroSrlrl",zeroMjss);
            srlrl.put("oneSrlrl",oneMjss);
        }else if(cityAverageSrlrlPerAcre != null && cityAverageSrlrlPerAcre.size() == 1){
            Map<String, Object> zeroMap = cityAverageSrlrlPerAcre.get(0);
            String zeroCity = (String)zeroMap.get("city");
            Object zeroMjss = zeroMap.get("srlrl");
            srlrl.put("city",zeroCity);
            srlrl.put("zeroSrlrl",zeroMjss);
            srlrl.put("oneSrlrl","0");
        }
        resultMap.put("srlrl",srlrl);


        //计算亩均销售收入
        List<Map<String, Object>> averageSalesIncomePerAcre = preMuGenDocxMapper.queryAverageSalesIncomePerAcre();
        Map<String,Object> mjxs = new HashMap<>();

        if(averageSalesIncomePerAcre != null && averageSalesIncomePerAcre.size() == 2){
            Map<String, Object> zeroMap = averageSalesIncomePerAcre.get(0);
            Map<String, Object> oneMap = averageSalesIncomePerAcre.get(1);
            String zeroCity = (String) zeroMap.get("city");
            String oneCity =(String) oneMap.get("city");
            Object zeroMjxs = zeroMap.get("mjxs");
            Object oneMjxs= oneMap.get("mjxs");
            mjxs.put("city",zeroCity + "、" + oneCity);
            mjxs.put("zeroMjss",zeroMjxs);
            mjxs.put("oneMjss",oneMjxs);
        }else if(averageSalesIncomePerAcre != null && averageSalesIncomePerAcre.size() == 1){
            Map<String, Object> zeroMap = averageSalesIncomePerAcre.get(0);
            String zeroCity = (String) zeroMap.get("city");
            String zeroMjss =(String)zeroMap.get("mjxs");
            mjxs.put("city",zeroCity);
            mjxs.put("zeroMjss",zeroMjss);
            mjxs.put("oneMjss","0");
        }
        resultMap.put("mjxs",mjxs);
        //单位能耗税收。2025把这个改成单位能耗收入（计算的字段变了）
        List<Map<String, Object>> unitEnergyTaxRevenue = preMuGenDocxMapper.queryUnitEnergyTaxRevenue();
        Map<String,Object> dwnhss = new HashMap<>();
        if(unitEnergyTaxRevenue != null && unitEnergyTaxRevenue.size() == 2){
            Map<String, Object> zeroMap = unitEnergyTaxRevenue.get(0);
            Map<String, Object> oneMap = unitEnergyTaxRevenue.get(1);
            String zeroCity = (String) zeroMap.get("city");
            String oneCity =  (String)oneMap.get("city");
            Object zeroMjss =  zeroMap.get("dwnh");
            Object oneMjss= oneMap.get("dwnh");
            dwnhss.put("zeroCity",zeroCity);
            dwnhss.put("oneCity",oneCity);
            dwnhss.put("zeroDwnh",zeroMjss);
            dwnhss.put("oneDwnh",oneMjss);
        }else if(unitEnergyTaxRevenue != null && unitEnergyTaxRevenue.size() == 1){
            Map<String, Object> zeroMap = unitEnergyTaxRevenue.get(0);
            String zeroCity = (String)zeroMap.get("city");
            String zeroMjss = (String)zeroMap.get("dwnh");
            dwnhss.put("city",zeroCity);
            dwnhss.put("zeroDwnh",zeroMjss);
            dwnhss.put("oneDwnh","0");
        }
        resultMap.put("dwnhss",dwnhss);
        return resultMap;
    }

    /**
     * 设置查询参数
     * @param queryParams
     */
    private void setQueryParams(PreMuBenefitEvaluation queryParams){
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        Set<String> roles= loginUser.getRoles();
//        if(roles.contains("x_01_011")||roles.contains("along_yellow_river")){
//            String county=  loginUser.getSysUser().getDistrict();
//            queryParams.setCounty(county);
//        }else if(roles.contains("s_01_011")){
//            String city=  loginUser.getSysUser().getCity();
//            queryParams.setCity(city);
//        }else if(roles.contains("p_01_011")){
//            String province=  loginUser.getSysUser().getProvince();
//            queryParams.setProvince(province);
//        }
    }
}
